/**
 * @param {string} s
 * @return {string}
 */
 var minRemoveToMakeValid = function(s) {
  let res = ''
  let arr = []
  let count
  for(let i=0;i<s.length;i++){
    if(s[i]>='a'&&s[i]<='z'){
      res+=s[i]
    }else {
      if(s[i]=='('){
        arr.push(i-arr.length)
      
      }else {
        if(arr.length>0){
          res+=s[i]
          let t = arr.pop()
          res=res.substring(0,t)+'('+res.substring(t)
        }else {
          res = ')'+res
          count++
        }
      }
    }
  }
  return res.substring(count)
};

minRemoveToMakeValid("a)b(c)d")
